$(function () {
    //初始化滚动条监听及其他通用监听
    $(".row-config textarea").focus(function () {
        $(this)[0].select();
        getBrotherControls($(this)).btn_catalog.trigger("click");
        $(this).addClass("focus");
    });
    $(".row-config textarea").blur(function () {
        $(this).removeClass("focus");
        validRow($(this));
    });
    var ctn_config_inner = $("#ctn_config_inner"),
        ctn_config_total = $("#ctn_config_total"),
        ctn_config_info = $("#ctn_config_info"),
        h_title = $("#h_title"),
        navbar = $(".navbar"),
        path_itemImg = $("#hid_PATH_ITEMIMG").val(),
        path_noImg = $("#hid_PATH_NOIMG").val(),
        totalHeight = ctn_config_total.height(),
        windowHeight = $(window).height();
    var scrollLimitHeight = ctn_config_inner.height() + h_title.height() + navbar.height();
    //console.log(scrollLimitHeight);
    ctnConfigTotalResize();
    function ctnConfigTotalResize() {
        var wd = ctn_config_inner.width();
        ctn_config_total.width(wd);
        windowHeight = $(window).height();
        scrollLimitHeight = ctn_config_inner.height() + h_title.height() + navbar.height();
    }
    $(window).resize(ctnConfigTotalResize);
    $(window).scroll(function () {
        var sh = $(window).scrollTop() + windowHeight;
        if (sh >= scrollLimitHeight) {
            ctn_config_total.removeClass("fixed");
        } else {
            ctn_config_total.addClass("fixed");
        }
    });

    //functions
    var ctn_condi_fields = $("#ctn_condi_fields"),
        ctn_item_list = $(".ctn-item-list"),
        lbl_title_condi = $("#lbl_title_condi"),
        lbl_total_qty = $(".lbl-total-qty"),
        lbl_total_amount = $(".lbl-total-amount"),
        btn_cart_clear = $(".btn-cart-clear"),
        txt_condi_search = $("#txt_condi_search"),
        btn_condi_search = $("#btn_condi_search"),
        sel_name = ".ctn-sel-itemName textarea",
        sel_qty = ".ctn-sel-itemQty textarea",
        sel_price = ".ctn-sel-itemPrice textarea",
        sel_delete = ".ctn-sel-itemDelete .btn-del-config",
        sel_catalog = ".ctn-sel-itemCatalog .btn-sel-config",
        //btn_print = $("#btn_print"),
        btn_submit = $("#btn_submit"),
        btn_preview = $("#btn_preview"),
        btn_changeVC = $(".a-verifidationCode"),
        txt_validationCode = $("#txt_validationCode"),
        txt_config_title = $("#txt_config_title"),
        txt_config_username = $("#txt_config_username"),
        txt_config_info = $("#txt_config_info"),
        cbo_config_type = $("#cbo_config_type"),
        hid_ST_M_GUID = $("#hid_ST_M_GUID");
    var viiio_catalog_guid = $(".row-config:first").data("guid"),
        viiio_catalog_area = $(".row-config:first").data("area"),
        viiio_cart = {
            "items": {//Dictionary
                "guidKey": {
                    "name": "",
                    "qty": 0,
                    "amt": 0,
                    "totamt": 0
                }
            },
            "totamt": 0,
            "totqty": 0
        },
        viiio_dic_condi = {};//temprory condi
    var viiio_search_model = {
        "catalog": viiio_catalog_guid,
        "brand": "",
        "price": "",
        "searchCondi": [],
        "textCondi": "",
        "orderby": "h_asc"
    };
    var viiio_req = {
        "user": {
            "usercode": "",
            "token": "",
            "remain": ""
        },
        "page": {
            "pageIndex": 1,
            "pageSize": 8
        }
        , "viiioData": null
    };


    //=======item Select/Edit=========
    //选中单item
    ctn_item_list.on("click", ".btn-item-select", function () {
        $this = $(this);
        var r_item = $this.closest(".row-item-list");
        var c_guid = r_item.data("guid"),
            i_name = r_item.find(".a-item-name").data("name"),
            i_price = r_item.find(".p-price").data("price"),
            r_config = $(".row-config[data-guid='" + c_guid + "']");
        r_ctrls = getSubControls(r_config);
        r_ctrls.txt_name.val(i_name);
        r_ctrls.txt_qty.val("1");
        r_ctrls.txt_price.val(i_price);
        validRow(r_ctrls.btn_catalog);
    });

    //Config Row Control Events
    //切换目录
    $(sel_catalog).click(function () {
        var r_ctrls = getBrotherControls($(this));
        viiio_catalog_guid = r_ctrls.st_guid;
        lbl_title_condi.text(r_ctrls.st_area);
        getCatalogFields();
    });
    //删除行
    $(sel_delete).click(function () {
        var r_ctrls = getBrotherControls($(this));
        //clear row data
        clearRowData(r_ctrls);
        //then remove item in cart
        validRow($(this));
    });
    //编辑qty price
    $(sel_qty + "," + sel_price).focus(function () {
        var txt_name = getBrotherControls($(this)).txt_name;
        var st_name = $.trim(txt_name.val());
        if (st_name.length == 0) {
            txt_name.focus();
            return false;
        }
    });
    btn_cart_clear.click(function () {
        viiio_cart.items = {};
        $(".row-config textarea").val("");
        reCalcCart();
    });
    //检测行数据合法
    function validRow($ctrl) {
        var r_ctrls = getBrotherControls($ctrl),
            reg_allowNull = /^\d*$/,
            reg = /^\d{1,}$/;
        if (r_ctrls.txt_price.val().match(reg_allowNull) == null) {
            r_ctrls.txt_price.val("");
        }
        if (r_ctrls.txt_qty.val().match(reg) == null) {
            r_ctrls.txt_qty.val("1");
        }
        if ($.trim(r_ctrls.txt_name.val()).length == 0) {
            //clear row data
            clearRowData(r_ctrls);
        }
        saveCartItem($ctrl);
    }
    //清空行，不重算
    function clearRowData(r_ctrls) {
        r_ctrls.txt_name.val("");
        r_ctrls.txt_price.val("");
        r_ctrls.txt_qty.val("");
    }
    //购物车货品保存
    function saveCartItem($ctrl) {
        var r_ctrls = getBrotherControls($ctrl);
        if ($.trim(r_ctrls.txt_name.val()).length == 0) {
            viiio_cart.items[r_ctrls.st_guid] = null;
        } else {
            var i_item = getCartItem();
            i_item.name = encodeURIComponent($.trim(r_ctrls.txt_name.val()));
            i_item.qty = parseInt(r_ctrls.txt_qty.val().length == 0 ? 1 : r_ctrls.txt_qty.val());
            i_item.amt = parseFloat(r_ctrls.txt_price.val().length == 0 ? 0 : r_ctrls.txt_price.val());
            i_item.totamt = i_item.qty * i_item.amt;
            i_item.catalog = r_ctrls.st_guid;
            viiio_cart.items[r_ctrls.st_guid] = i_item;
        }
        reCalcCart();
    }
    //重计算总数
    function reCalcCart() {
        var totqty = 0, totamt = 0;
        for (var key in viiio_cart.items) {
            if (viiio_cart.items[key]) {
                var i_item = viiio_cart.items[key];
                totamt += i_item.totamt;
                totqty += i_item.qty;
            }
        }
        viiio_cart.totqty = totqty;
        viiio_cart.totamt = totamt;
        lbl_total_qty.html(totqty);
        lbl_total_amount.html(totamt);
    }
    //购物车Item
    function getCartItem() {
        return {
            "name": "",
            "qty": 0,
            "amt": 0,
            "totamt": 0,
            "catalog": ""
        };
    };
    function getConfigRow($ctrl) {
        return $ctrl.closest(".row-config");
    }
    function getBrotherControls($ctrl) {
        return getSubControls(getConfigRow($ctrl));
    }
    function getSubControls($r_config) {
        return {
            "txt_name": $r_config.find(sel_name),
            "txt_qty": $r_config.find(sel_qty),
            "txt_price": $r_config.find(sel_price),
            "btn_delete": $r_config.find(sel_delete),
            "btn_catalog": $r_config.find(sel_catalog),
            "st_guid": $r_config.data("guid"),
            "st_area": $r_config.data("area")
        };
    }
    function getCatalogFields() {
        if (viiio_req.viiioData == null || viiio_catalog_guid != viiio_search_model.catalog) {//阻止多次触发
            viiio_req.viiioData = viiio_catalog_guid;
            viiio_search_model.catalog = viiio_catalog_guid;
            viiio_search_model.searchCondi = [];
            viiio_search_model.brand = "";
            viiio_search_model.price = "";
            viiio_dic_condi = {};
            viiio_search_model.textCondi = "";
            txt_condi_search.val("");
            ajaxPost("diycatalog", viiio_req, function (data) {
                if (data.errorCode == 0) {
                    initCatalogItems();//不能放在post外部，否则浏览器阻止同时请求导致阻塞
                    ctn_condi_fields.empty();
                    for (var i = 0; i < data.data.fields.length; i++) {
                        f = data.data.fields[i];
                        var r_field = $("<div class=\"ctn-sel-condi clearfix\" data-guid=\"" + f.field.ST_GUID + "\"></div>");
                        $("<span class=\"desc-sel-condi\">" + f.field.ST_NAME + "：</span>").appendTo(r_field);
                        var v_field = $("<div class=\"list-sel-condi\"></div>");
                        $("<a href=\"javascript:;\" class=\"item-sel-condi selected\">不限</a>").appendTo(v_field);
                        for (var j = 0; j < f.fieldValues.length; j++) {
                            v = f.fieldValues[j];
                            $("<a href=\"javascript:;\" class=\"item-sel-condi\" data-guid=\"" + v.ST_GUID + "\">" + v.ST_NAME + "</a>").appendTo(v_field);
                        }
                        v_field.appendTo(r_field);
                        r_field.appendTo(ctn_condi_fields);
                    }
                } else {
                    ctn_condi_fields.html(data.errorMsg);
                }
            });
        }
    }
    getCatalogFields();
    //===========field value select==========
    ctn_condi_fields.on("click", ".item-sel-condi", function () {
        $this = $(this);
        $this.parent().children(".selected").removeClass("selected");
        $this.addClass("selected");
        var f_guid = $this.parent().parent().data("guid");
        var v_guid = $this.data("guid");
        if (f_guid == "brand") {
            viiio_search_model.brand = v_guid;
        } else if (f_guid == "price") {
            viiio_search_model.price = v_guid;
        } else {
            viiio_dic_condi[f_guid] = v_guid;
            var sc = [];// 
            for (var key in viiio_dic_condi) {
                if (viiio_dic_condi[key] != null) {
                    sc.push(viiio_dic_condi[key]);
                }
            }
            viiio_search_model.searchCondi = sc.length == 0 ? null : sc;
        }
        initCatalogItems();
    });
    //排序
    $("#ctn_condi_orderby button").click(function () {
        $this = $(this);
        if (!$this.hasClass("btn-danger")) {
            $this.parent().children().removeClass("btn-danger");
            $this.addClass("btn-danger");
            viiio_search_model.orderby = $this.data("orderby");
            initCatalogItems();
        }
    });
    //Search
    btn_condi_search.click(function () {
        viiio_search_model.textCondi = encodeURIComponent($.trim(txt_condi_search.val()));
        initCatalogItems();
    });
    txt_condi_search.focus(function () { txt_condi_search[0].select(); });
    txt_condi_search.on("keyup", function () {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode == 13) { // enter 键
            btn_condi_search.focus();
            btn_condi_search.trigger("click");
        }
    });
    //===========load data=============
    function initCatalogItems() {
        viiio_req.page.pageIndex = 1;
        getCatalogItems();
    }
    function getCatalogItemsByPage(pgindex) {
        viiio_req.page.pageIndex = pgindex;
        getCatalogItems();
    }
    function getCatalogItems() {
        viiio_req.viiioData = viiio_search_model;
        ajaxPostItem("diyitem", viiio_req, function (data) {
            if (data.errorCode == 0) {
                ctn_item_list.empty();
                initPagination(data.pager.pageTotal, data.pager.pageIndex);
                for (var i = 0; i < data.data.length; i++) {
                    var item = data.data[i];
                    var itemImgURL = item.ST_IMG == null ? path_noImg : path_itemImg + item.ST_IMG
                    var itemTemplate = "<div class=\"row-item-list clearfix\" data-guid=\"" + item.ST_CATALOG_LV2_GUID + "\"> \
                                        <div class=\"col-xs-12 col-md-7 padding-l-10\"> \
                                            <div class=\"col-xs-3 ctn-item-img padding5\"> \
                                                <a target=\"_blank\" href=\"/item/" + item.ST_GUID + "\"> \
                                                    <img class=\"wd50 fadeInDown animated\" alt=\"" + item.ST_WEBNAME + "\" src=\"" + itemImgURL + "\" onerror=\"this.src='" + path_noImg + "'\"/> \
                                                </a> \
                                            </div> \
                                            <div class=\"col-xs-9 ctn-item-name\"> \
                                                <a class=\"a-item-name wordwrap\" target=\"_blank\" href=\"/item/" + item.ST_GUID + "\" data-name=\"" + item.ST_WEBNAME + "\" title=\"" + item.ST_WEBNAME + "\"> \
                                                    " + item.ST_WEBNAME + " \
                                                </a> \
                                            </div> \
                                        </div> \
                                        <div class=\"col-xs-12 col-md-5\" style=\"padding-right: 0px;\"> \
                                            <div class=\"col-xs-4 ctn-item-price text-left clr-price bold font14px padding-t-15\"> \
                                                <span class=\"p-price\" data-price=\"" + item.NO_P_SELLING + "\" style=\"margin-left:-15px;\">\¥ <label class=\"l-price\">" + item.NO_P_SELLING + "</label></span> \
                                            </div> \
                                            <div class=\"col-xs-4 ctn-item-morePrice text-left\" style=\"padding:17px 0 0;\"> \
                                                <a href=\"javascript:;\" style=\"margin-top:2px;\"> \
                                                    更多报价 \
                                                </a> \
                                            </div> \
                                            <div class=\"col-xs-4 ctn-item-select text-center\" style=\"padding:10px 0 0;\"> \
                                                <button class=\"btn btn-item-select btn-info btn-sm col-xs-10\" type=\"button\">\选中</button> \
                                            </div> \
                                        </div> \
                                    </div>";
                    $(itemTemplate).appendTo(ctn_item_list);
                }
            } else if (data.errorCode == 404) {
                ctn_item_list.html("<div class=\"text-center margin-t-20 margin-b-20\">没有东西喔~改变搜索条件再试试~</div>");
            } else {
                ctn_item_list.html(data.errorMsg);
            }
        }, function () {
            ctn_item_list.html("<div class=\"text-center margin-t-20 margin-b-20\"><img src=\"/images/global/loading_01.gif\" /></div>");
        }, function () {

        });
    }

    //=======load saved configuration=======
    if ($.trim(hid_ST_M_GUID.val()).length > 0) {
        $(".row-config").each(function () {
            if ($(this).data("guid").length > 0) {
                validRow(getSubControls($(this)).btn_catalog);
            }
        });
    }


    //===========submit================
    var dlg = new BootstrapDialog({
        title: '大侠，留个名儿吧',
        message: ctn_config_info,
        buttons: [{
            label: '再改改',
            action: function (dialogRef) {
                ctn_config_info.hide();
                dialogRef.close();
            },
            icon: 'glyphicon glyphicon-pencil',
        }]
    });
    function validConfig() {
        //至少选择CPU、主板、内存
        var arr_notnull = ["530C423A-5C0E-47BF-A5B2-E33FB3C3EFAB", "974CA224-7CAF-47E2-A09E-5D29DE766992", "0648B7D8-9CAA-4ADD-B070-245FC150BCCC"];
        for (var i = 0; i < arr_notnull.length; i++) {
            var st_guid = arr_notnull[i];
            var isValid = true;
            if (!viiio_cart.items[st_guid]) {
                isValid = false;
                break;
            }
        }
        if (!isValid) {
            $.scojs_message("至少需要选择CPU、主板和内存！", $.scojs_message.TYPE_ERROR);
            return false;
        }
        return true;
    }
    btn_submit.click(function () {
        if (validConfig()) {
            ctn_config_info.show();
            dlg.open();
            btn_changeVC.trigger("click");
        }
    });
    btn_changeVC.click(function () {
        $("#img_vc").trigger("click");
    });
    btn_preview.click(function (e) {
        e.preventDefault();
        if (validConfig()) {
            var l = Ladda.create(this);
            l.start();
            $this = $(this);
            if ($.trim(txt_config_title.val()).length == 0) {
                txt_config_title.focus();
                l.stop();
                return;
            }
            if ($.trim(txt_validationCode.val()).length == 0) {
                txt_validationCode.focus();
                l.stop();
                return;
            }
            //开始构筑配置单对象
            var dic_item = viiio_cart.items;
            var configuration = {
                "items": [],
                "totamt": 0,
                "totqty": 0,
                "configName": encodeURIComponent($.trim(txt_config_title.val())),
                "userName": encodeURIComponent($.trim(txt_config_username.val())),
                "configInfo": encodeURIComponent($.trim(txt_config_info.val())),
                "projectType": cbo_config_type.val(),
                "vc": $.trim(txt_validationCode.val())
            };
            configuration.totqty = viiio_cart.totamt;
            configuration.totqty = viiio_cart.totqty;

            for (var key in dic_item) {
                var item = dic_item[key];
                if (item && item.catalog != null && item.qty >= 0 && item.amt >= 0) {
                    configuration.items.push(dic_item[key]);
                }
            }
            viiio_req.viiioData = configuration;
            $.ajaxControl({
                actionURL: "/api/common",
                Controller: "diysubmit",
                Data: JSON.stringify(viiio_req),
                callback: function (data) {
                    if (data.errorCode == 0) {
                        $.scojs_message("配置单提交成功~！", $.scojs_message.TYPE_OK);
                        location.replace("/pz/" + data.data);
                    } else {
                        if (data.errorCode == 403) {
                            txt_validationCode.focus();
                        } else {
                            btn_submit.trigger("click");
                        }
                        $.scojs_message(data.errorMsg, $.scojs_message.TYPE_ERROR);
                    }
                },
                show_shade: function () { $.scojs_message("提交中...", $.scojs_message.TYPE_OK); },
                close_shade: function () {
                    l.stop();
                }
            });
        }
    });

    //分页器
    num_entries = 1; //全局PAGE_COUNT對象
    //initPagination(1, 1);
    function initPagination(num_pagetot, pageNo) {
        // 创建分页
        $("#Pagination").pagination(num_pagetot, {
            current_page: pageNo - 1,
            num_edge_entries: 1, //边缘页数
            num_display_entries: 4, //主体页数
            callback: pageSelectCallback,
            items_per_page: 1, //每页显示1项
            prev_text: "<span class=\"glyphicon glyphicon-chevron-left pg-xs\" aria-hidden=\"true\"></span>",
            next_text: "<span class=\"glyphicon glyphicon-chevron-right pg-xs\" aria-hidden=\"true\"></span>",
            link_to: "javascript:;"
        });
    };
    function pageSelectCallback(page_index, jq) {
        var page = page_index + 1;
        //drawGraph(page);
        getCatalogItemsByPage(page);
        return false;
    }

    var Aj, Aj_item;
    function ajaxPost(ctrl, data, cb) {
        if (Aj) {
            AJ.abort();
        }
        Aj = $.ajaxControl({ actionURL: "/api/common", Controller: ctrl, Data: JSON.stringify(data), callback: cb });
    }
    function ajaxPostItem(ctrl, data, cb, show_shade, close_shade) {
        if (Aj_item) {
            Aj_item.abort();
        }
        var IsPosting = true;
        Aj_item = $.ajaxControl({
            actionURL: "/api/common", Controller: ctrl, Data: JSON.stringify(data), callback: cb,
            show_shade: function () {
                //低于300毫秒的请求不显示Loading
                setTimeout(function () {
                    if (IsPosting) {
                        show_shade();
                    }
                }, 100);
            },
            close_shade: function () {
                IsPosting = false;
                close_shade();
            }
        });
    }
});